package com.lepu.app.fun.tool.bbcsz;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import lib.share.utils.CallBack;
import lib.share.utils.ShareLib;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.ProgressBar;

import com.app.application.MyApplication;
import com.app.utils.AppEnterTongJi;
import com.app.utils.AppWebChromClient;
import com.app.utils.DateUtil;
import com.app.utils.LoginUtil;
import com.app.utils.SdLocal;
import com.app.utils.Setting;
import com.app.utils.Utils;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.BrowserWebChromeClient.BrowserWebChromeDelegate;
import com.core.lib.utils.BrowserWebClient;
import com.core.lib.utils.BrowserWebClient.BrowserWebClientDelegate;
import com.core.lib.utils.main.ImageUtilBase;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.eyzhs.app.R;
import com.lepu.app.fun.tool.bbcsz.bean.BeanToolBbcs;
import com.lepu.app.main.activity.AppBroswerActivityBase;
import com.lepu.app.usercenter.bean.LoginInfo;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewRightButtonListener;

public class BbcsShowActivity extends AppBroswerActivityBase implements
		OnTopbarNewLeftLayoutListener,OnTopbarNewRightButtonListener, AsyncRequest, BrowserWebChromeDelegate,
		BrowserWebClientDelegate {

	private static final String REQUEST_YAOQING_SHARE = "request_yaoqing_share";

	private static final String GOTO_SAVE = "goto::save";
	private static final String GOTO_SHARE = "goto::share";
	
	private static final int MSG_SAVE_SUCCESS = 11;
	private static final int MSG_SAVE_SHARE_SUCCESS = 12;

	public String mTargetUrl = "";

	public String  mImagePath = "";
	
	private WebView mWebView = null;
	private ProgressBar mProgressBar = null;

	private CustomTopBarNew mTopbar = null;
	
	private boolean doShare = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {

		mNeedSwipeBack = false;
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tool_bbcs_show_activity);

		init();
	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@Override
	public void onResume() {
		mWebView.onResume();
		super.onResume();
	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@Override
	public void onPause() {
		mWebView.onPause();
		super.onPause();
	}

	@Override
	public void onDestroy() {
		mWebView.destroy();

		super.onDestroy();
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		finishAnim(R.anim.lib_push_down_up_in, R.anim.lib_push_down_up_out);
	}

	@Override
	public void onTopbarLeftLayoutSelected() {
		finishAnim(R.anim.lib_push_down_up_in, R.anim.lib_push_down_up_out);
	}
	
	@Override
	public void onTopbarRightButtonSelected() {
		finish(true);
	}

	/**
	 * 初始化方法
	 */
	@SuppressLint("SetJavaScriptEnabled")
	private void init() {
		// topbar
		mTopbar = (CustomTopBarNew) findViewById(R.id.topbar);
		mTopbar.setTopbarTitle("宝宝出生证");
		mTopbar.setonTopbarNewLeftLayoutListener(this);
		mTopbar.setOnTopbarNewRightButtonListener(this);
		mTopbar.setRightText("重新制作");

		mProgressBar = (ProgressBar) findViewById(R.id.topProgressBar);

		mWebView = (WebView) findViewById(R.id.webView);
		mWebView.setWebChromeClient(new AppWebChromClient(this,this, FILECHOOSER_RESULTCODE, REQUEST_SELECT_FILE));
		mWebView.setWebViewClient(new BrowserWebClient(this, this, mWebView));
		
		Utils.initWebViewSettings(mWebView, false);
		
		mWebView.addJavascriptInterface(new InJavaScriptLocalObj(), "load_obj");

		BeanToolBbcs bean = null;
		Bundle data = getIntent().getExtras();
		if(data != null && data.size() > 0){
			bean = (BeanToolBbcs) data.getSerializable("bbcs");
		}else{
			return;
		}

		String url = "http://dl.eyzhs.com/tools/birthCertificate.html?"+ 
		        "name=" + bean.babyName + 
				"&gender=" + bean.babySex+ 
				"&weight=" + bean.babyWeight + 
				"&father=" + bean.fatherName+ 
				"&mother=" + bean.motherName + 
				"&birthday=" + bean.babyDate+ " " + bean.babyTime;
		mWebView.loadUrl(url);
	}

	//goto 监听
	@Override
	public boolean shouldOverrideUrlLoading(WebView webView, String url) {
		//保存图片
		if (url.contains(GOTO_SAVE)) {
			doShare = false;
			mWebView.loadUrl("javascript:window.load_obj.showSource(getImage());");
		} 
		//分享
		else if (url.contains(GOTO_SHARE)) {
			if(TextUtils.isEmpty(mImagePath)){
				doShare = true;
				mWebView.loadUrl("javascript:window.load_obj.showSource(getImage());");
			}else{
				gotoShare();
			}
			
		}else {
			webView.loadUrl(url);
		}
		return true;
	}
	
	public void gotoShare() {

		File file = new File(mImagePath);
		if (!file.exists()) {
			doShare = true;
			mWebView.loadUrl("javascript:window.load_obj.showSource(getImage());");
			return;
		}
		
		// 调用官方sdk分享，可以各种形式
		ShareLib.Share(this, "", "", mImagePath, "", false,true,
				new CallBack() {
					@Override
					public void callBackSuccess(Object obj) {
						super.callBackSuccess(obj);

						requestShare();
						
					}
				});
		
		 AppEnterTongJi.clickEvent(82, "");
		
	}
	

	private void requestShare() {

		if (!MyApplication.getInstance().checkIsLogin()) {
			return;
		}

		String url = Setting.getShareSuccessUrl();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();

		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();
			params.put("UserID", loginInfo.UserID);
			params.put("LoginToken", loginInfo.LoginToken);

			params.put("ObjectType", 4);
			params.put("ObjectID", -1);
		} catch (Exception e) {
		}
		map.put("ht", params);

		ApiClient.http_post_main(url, map, null, this, REQUEST_YAOQING_SHARE,
				false);
	}

	@Override
	public void RequestComplete(Object object, Object data) {

		if (object.equals(REQUEST_YAOQING_SHARE)) {
			LogUtilBase.LogD(null, "share request_yaoqing_share success");
			try {
				JSONObject jsonObject = new JSONObject((String) data);
				JSONObject obj1 = (JSONObject) jsonObject.get("Result");
				JSONObject dataObject = (JSONObject) obj1.get("DetailInfo");

				int integral = dataObject.optInt("ChangeCredits");
				LoginUtil.jumpIntegral(BbcsShowActivity.this, integral);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if (object.equals(REQUEST_YAOQING_SHARE)) {
			LogUtilBase.LogD(null, "share request_yaoqing_share fail");
		}
	}
	
	
	//js回调  
    final class InJavaScriptLocalObj {
    	
    	@SuppressLint("NewApi")
		@JavascriptInterface
        public void showSource(String html) {
    		if(html.contains("data:image/png;base64,")){
    			html = html.replace("data:image/png;base64,", "");
    		}
    		
    		byte[] bytes = Base64.decode(html, Base64.DEFAULT); 
    		Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    		
    		String thisTime = String.valueOf(DateUtil.getNowTimeInMillis());
    		mImagePath = SdLocal.getBabyFolder(BbcsShowActivity.this)+"/"+thisTime+".jpg";
    		//
    		ImageUtilBase.saveImageToSd(bitmap, mImagePath);
    		
    		if(doShare){
    			Message msg = mHandler.obtainMessage();
    			msg.what = MSG_SAVE_SHARE_SUCCESS;
    			mHandler.sendMessage(msg);
    		}else{
    			 // 其次把文件插入到系统图库
        	    try {
        	        MediaStore.Images.Media.insertImage(getContentResolver(),mImagePath, thisTime+".jpg", null);
        	    } catch (FileNotFoundException e) {
        	        e.printStackTrace();
        	    }
        	    // 最后通知图库更新
        	    sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + mImagePath)));
        	    
        		Message msg = mHandler.obtainMessage();
    			msg.what = MSG_SAVE_SUCCESS;
    			mHandler.sendMessage(msg);
    		}
    	   
    	}
    }
	
    
	@SuppressLint("HandlerLeak")
	public Handler mHandler = new Handler() {

		public void handleMessage(Message msg) {

			switch (msg.what) {
			case MSG_SAVE_SUCCESS:
				UIHelper.showToast(BbcsShowActivity.this, "保存成功");
				break;
			case MSG_SAVE_SHARE_SUCCESS:
				gotoShare();
				break;
			default:
				break;
			}
		};
	};
	
	
	// ======================================================

	public void onProgressChanged(WebView view, int newProgress) {
		// LogUtilBase.LogD(null, "onProgressChanged===>>" + newProgress);
		mProgressBar.setMax(100);
		if (newProgress < 100) {
			if (mProgressBar.getVisibility() == View.GONE) {
				mProgressBar.setVisibility(View.VISIBLE);
			}
			mProgressBar.setProgress(newProgress);
		} else {
			mProgressBar.setProgress(100);

			Animation animation = AnimationUtils.loadAnimation(this,
					R.anim.lib_broswer_progress);
			// 运行动画
			mProgressBar.startAnimation(animation);
			// 将 spinner 的可见性设置为不可见状态
			mProgressBar.setVisibility(View.GONE);
		}
	}

	
	@Override
	public void onPageStarted(String arg0) {

	}

	@Override
	public void onPageFinished(String arg0) {
		
	}

}
